<template>
  <div class="user-page page-main">
    <search-form :model="searchParams" @search="search">
      <a-form-item label="角色名称" name="roleName">
        <a-input v-model:value="searchParams.roleName" placeholder="请输入" />
      </a-form-item>
    </search-form>
    <div class="table-toolbar">
      <add-button @click="add()" />
    </div>
    <g-table
      ref="tableRef"
      :columns="columns"
      :api="getRoles"
      :params="searchParams"
    />

    <RoleDetail
      v-model:visible="visible"
      :data="activeRow"
      @change="search(false)"
    />
  </div>
</template>

<script setup lang="tsx">
import { delRole, getRoles, updateRoleStatus } from "@/api/role";
import type { IRole } from "@/types/role";
import RoleDetail from "./detail.vue";

const searchParams = reactive({
  roleName: "",
});

let visible = $ref(false);

const { tableRef, columns, search } = useTable<IRole>([
  { title: "角色ID", dataIndex: "id", width: 80 },
  { title: "角色名称", dataIndex: "roleName", width: 100 },
  { title: "备注", dataIndex: "remark", width: 160, ellipsis: true },
  { title: "创建时间", dataIndex: "createTime", width: 180 },
  { title: "更新时间", dataIndex: "updateTime", width: 180 },
  {
    title: "状态",
    dataIndex: "status",
    width: 120,
    customRender: ({ record }) => (
      <>
        <a-switch
          onClick={() => toUpdateState(record)}
          v-model:checked={record.status}
          inline-prompt
          checkedChildren="开启"
          unCheckedChildren="关闭"
        />
      </>
    ),
  },
  {
    title: "操作",
    dataIndex: "op",
    width: 120,
    fixed: "right",
    customRender: ({ record }) => (
      <>
        <table-button onClick={() => add(record)}>编辑</table-button>
        <confirm-button danger onClick={() => remove(record)}>
          删除
        </confirm-button>
      </>
    ),
  },
]);

let activeRow = $ref<Partial<IRole>>({});
function add(row: Partial<IRole> = {}) {
  activeRow = { ...row };
  visible = true;
}

function remove({ id }: IRole) {
  delRole(id as number).then(() => {
    AntMessage.success("已删除");
    search(false);
  });
}
const toUpdateState = (row: any) => {
  updateState({ id: row.id, status: row.status });
};

const updateState = async (data: any) => {
  await updateRoleStatus(data);
  AntMessage.success("操作成功");
  search(false);
};
</script>

<style lang="less"></style>
